//
//  UserAccount.swift
//  MyMicroBlog
//
//  Created by H on 15/8/3.
//  Copyright © 2015年 H. All rights reserved.
//

import UIKit

class UserAccount: NSObject,NSCoding{
class var userLogon:Bool {
    
    return sharedUserAccount != nil
    }

   /* access_token	string	用于调用access_token，接口获取授权后的access token。
    expires_in	string	access_token的生命周期，单位是秒数。
    uid	string	当前授权用户的UID。
*/
//    用于调用access_token，接口获取授权后的access token。
    var access_token:String?
//    access_token的生命周期，单位是秒数。
    var expires_in:NSTimeInterval = 0 {
        didSet{
        
         expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    //转换过期日期的显示格式
    var expiresDate:NSDate?
//    当前授权用户的UID。
    var  uid:String?
    //	友好显示名称
    var name:String?
    //用户头像地址（大图），180×180像素
    var  avatar_large:String?
    
    init(dict:[String:AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
        //设置全局的用户信息
        UserAccount.userAccount = self
       
    }

    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    //调试模型信息,对象描述信息
    override var description: String {
        let dict = ["access_token", "expires_in", "uid","expiresDate","name","avatar_large"]
        
        return "\(dictionaryWithValuesForKeys(dict))"
    }
    //MARK:-加载用户信息
    func loadUserInfo(finished:((error:NSError?)->())){
    NetworkTools.sharedNetworkTools.loadUserInfo(uid!) { (result, error) -> () in
        if error != nil {
            finished(error: error)
            return
        }
        // 设置用户信息
        self.name = result!["name"] as? String
        self.avatar_large = result!["avatar_large"] as? String
        
        // 保存用户信息
        self.saveAccount()
        print(self)
        //完成回调
        finished(error:nil)
        
        }
    
    }
    //归档和解档的路径
    static private let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingPathComponent("account.plist")
    
    /// 保存用户账号
    func saveAccount() {
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)
        print(UserAccount.accountPath)
    }
    //读取用户账户
    //利用静态成员变量缓存
    private static var userAccount: UserAccount?
    class var sharedUserAccount : UserAccount? {
    
//        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount {
//                            // 判断 token 是否过期，过期日期 > 当前日期，表示没有过期
//                            if account.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
//                                return account
//                            }
//                        }
//        return nil
        if  userAccount == nil {
        userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount
        
        }
        // userAccount!.expiresDate = NSDate(timeIntervalSinceNow: -100)
        if let date = userAccount?.expiresDate where date.compare(NSDate()) == NSComparisonResult.OrderedAscending {
            // 如果已经过期，需要清空账号记录
            userAccount = nil
        }
        return userAccount
    }
//
//    //保存文件的路径
//   static  prvate  let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentationDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingPathComponent("account.plist")
//    //保存用户账号
//    func saveAccount(){
//    NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)
////    print(UserAccount.accountPath)
//    }
    
    // MARK: - NSCoding
    /// `归`档 -> 保存，将自定义对象转换成二进制数据保存到磁盘
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    /// `解`档 -> 恢复 将二进制数据从磁盘恢复成自定义对象
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String

    }

}
